<template>
  <view> </view>
</template>

<script>
import { initUser } from '@/config/api'
import InitWx from '@/mixins/init-wx'
import { getCurExternalContact } from '@/util/wxConfig.js'
export default {
  mixins: [InitWx],
  data() {
    return {
      // agentId: "1000052",
      agentId: '1000051',
      appid: 'ww7b2aa4df9044d73e',
      // agentId: '1000006', //知音眼镜
      // appid: 'ww200eba22d7a52732',
      host: '',
    }
  },
  async onLoad() {
    uni.showLoading({
      title: '加载中',
    })
    this.host = window.location.host
    let type = await this.getParams(window.location.href)
    if (type.type) {
      uni.setStorageSync('type', type.type)
    }
    //如果没有登录 且 没有code < 0 &&
    if (window.location.href.indexOf('code') < 0) {
      let redirect_uri = encodeURIComponent(window.location.host + '/h5')
      uni.hideLoading()
      window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_base&state=STATE&agentid=${this.agentId}#wechat_redirect`
    }
    //如果有code   未登录 >= 0 &&
    if (window.location.href.indexOf('code') >= 0) {
      let obj = await this.getParams(window.location.href)
      this.getUserInfo(obj)
    }
  },
  onReady() {},
  methods: {
    async getParams(url) {
      return new Promise((resolve, reject) => {
        var params = url.split('?')[1]
        if (!params) return null
        var arr = params.split('&')
        var o = {}
        for (var i = 0; i < arr.length; i++) {
          var tmpArr = arr[i].split('=')
          var key = tmpArr[0]
          var value = tmpArr[1]
          o[key] = value
        }
        resolve(o)
      })
    },
    async getUserInfo(obj) {
      let res = await initUser({
        code: obj.code,
      })
      uni.hideLoading()
      if (!res.userid) {
        window.location.href = `https://${window.location.host}/h5/`
      }
      uni.setStorageSync('UserId', res.userid)
      // 必须重定向 去掉参数的code  否则签名失败  根据type 决定跳转到哪里
      if (uni.getStorageSync('type') == 1) {
        window.location.href = `https://${window.location.host}/h5/#/pages/client/index`
      } else if (uni.getStorageSync('type') == 2) {
        window.location.href = `https://${window.location.host}/h5/#/pages/base/index`
      }
    },
  },
}
</script>

